﻿using System.Configuration;
using System.Xml;

namespace Cache.MemCache
{
    public class MemCachedSection
    {
        public static MemCachedConfig GetConfig()
        {
            var section = ConfigurationManager.GetSection("Cache") as XmlNode;

            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "memcached")
                {
                    return ParseConfig(child);
                }
            }
            return null;
        }

        private static MemCachedConfig ParseConfig(XmlNode section)
        {
            var config = new MemCachedConfig();
            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "setting")
                {
                    if (child.Attributes["IsCache"] != null)
                    {
                        config.IsCache = bool.Parse(child.Attributes["IsCache"].Value);
                    }
                    if (child.Attributes["SendReceiveTimeout"] != null)
                    {
                        config.SendReceiveTimeout = int.Parse(child.Attributes["SendReceiveTimeout"].Value);
                    }
                    if (child.Attributes["MinPoolSize"] != null)
                    {
                        config.MinPoolSize = int.Parse(child.Attributes["MinPoolSize"].Value);
                    }
                    if (child.Attributes["MaxPoolSize"] != null)
                    {
                        config.MaxPoolSize = int.Parse(child.Attributes["MaxPoolSize"].Value);
                    }
                }
                else if (child.Name.ToLower() == "add")
                {
                    var node = new MemCachedNode();
                    if (child.Attributes["name"] != null)
                    {
                        node.Name = child.Attributes["name"].Value;
                    }
                    if (child.Attributes["Hosts"] != null)
                    {
                        node.Hosts = child.Attributes["Hosts"].Value;
                    }
                    if (child.Attributes["KeyPrefix"] != null)
                    {
                        node.KeyPrefix = child.Attributes["KeyPrefix"].Value;
                    }
                    config.Nodes.Add(node.Name, node);
                }
            }
            return config;
        }
    }
}